<template>
  <div class="container">
    <div class="info-box">

      <div class="info-l">
        <div class="info-l-t">
          <el-avatar shape="square" :size="100" :src="ruleForm.avatar || defaultSrc" />
          <span class="user-name">{{ ruleForm.username }}</span>
        </div>
        <div class="info-l-b">
          <ul>
            <li
              v-for="item in leftList"
              :key="item.id"
              @click="handlerClick(item)"
            >
              {{ item.title }}
            </li>
          </ul>
        </div>
      </div>

      <div class="info-r">
        <h3 class="info-r-title">个人信息展示</h3>
        <div class="show-info">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
          > 
            <el-form-item label="用户id" prop="user_id">
              <el-input 
                v-model="ruleForm.user_id" 
                type="text" 
                disabled 
              />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="ruleForm.username" 
                type="text"
                disabled
              />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input   
                v-model="ruleForm.password" 
                type="password" 
                :disabled="isEdit"
              />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="ruleForm.gender" :disabled="isEdit">
                <el-radio label="男" border>男</el-radio>
                <el-radio label="女" border>女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="权限" prop="manager">
              <el-radio-group v-model="ruleForm.manager" disabled>
                <el-radio label="1" border>管理员</el-radio>
                <el-radio label="0" border>用户</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="ruleForm.email" 
                type="email"
                :disabled="isEdit"
               />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="ruleForm.phone" 
                type="text" 
                :disabled="isEdit"
              />
            </el-form-item>
            <el-form-item label="注册时间" prop="register_time">
              <el-input 
                v-model="ruleForm.register_time" 
                type="date" 
                disabled
              />
            </el-form-item>
            <div class="btns">
              <el-form-item v-show="isEdit">
                <el-button type="primary" @click="isEdit = false"
                  >编辑</el-button
                >
              </el-form-item>
              <el-form-item v-show="!isEdit">
                <el-button type="success" @click="updateUserInfo(ruleFormRef)"
                  >提交修改</el-button
                >
              </el-form-item>
              <el-form-item v-show="!isEdit">
                <el-button type="primary" @click="isEdit = true"
                  >取消编辑</el-button
                >
              </el-form-item>
            </div>

          </el-form>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
// vuex
import { onBeforeMount, watchEffect } from 'vue';
import { useStore } from 'vuex'
//element-plus
import { ElMessage } from 'element-plus'
// api
import userModelApi from '@/request/api/user.js';
import { useRouter } from 'vue-router';

// router
const router = useRouter();

const store = useStore();

// 默认图片路径
const defaultSrc = 'src/assets/default-avatar.jpg'

// leftList
const leftList = ref([
  {
    id: 1,
    title: '首页',
    path: '/'
  },
  {
    id: 2,
    title: '购物车',
    path: '/cart'
  },
  {
    id: 3,
    title: '订单中心',
    path: '/order'
  },
  {
    id: 4,
    title: '我的消息',
  },
])

// 点击每一项执行
const handlerClick = ( listItem ) => {
  if(listItem.path){
    router.push(listItem.path)
  }else{
    ElNotification({
      title: '我的消息',
      message: '暂无消息',
      type: 'info',
    })
  }
}

// 获取表单实例
const ruleFormRef = ref()

// 数据
let ruleForm = reactive({
  user_id: '',
  avatar: '',
  username: '',
  password: '',
  gender: '',
  manager: '',
  email: '',
  phone: '',
  register_time: ''
})

// 是否可编辑
let isEdit = ref(true);

// 确认邮箱
const checkEmail = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入邮箱'))
  } else if (value.indexOf('@') == -1) {
    callback(new Error("邮箱格式不正确"))
  } else {
    callback()
  }
}

// 确认手机号
const checkPhone = (rule, value, callback) => {
  const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (!reg.test(value)) {
    callback(new Error("请输入正确的手机号"))
  } else {
    callback()
  }
}


// 校验规则(自定义)
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在3-12之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12之间', trigger: 'blur' },
  ],
  gender: [
    { required: true }
  ],
  email: [
    { validator: checkEmail, required: true, trigger: 'blur' }
  ],
  phone: [
    { validator: checkPhone, required: true, trigger: 'blur' }
  ]
})

// 从vuex中把用户信息取出 并回显
watchEffect(() => {
  ruleForm = store.state.user.userInfo
})

// 修改用户信息 发送请求
const updateUserInfo = ( formEl ) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let params = {};
      for(let key in ruleForm){
        if(key == 'register_time') continue;
        params[key] = ruleForm[key]
      }

      const res = await userModelApi.editUserApi(params);

      // 重新获取用户信息
      userModelApi.getUserInfoApi().then(res => {
        // 重新赋值vuex
        // store.commit('setUserInfo',JSON.stringify(res.data));
        store.dispatch('asySetUserInfo', res.data);
        isEdit.value = true;
        ElMessage({
          type: 'success',
          message: '修改成功',
        })
        // location.reload();
      })
    } else {
      ElMessage.error('校验未通过,请输入正确的格式');
      return false
    }
  })
}

</script>

<style lang='less' scoped>
.container{
  width: 100%;
  height: 100%;
  background: url('../../assets/info-bg.png') no-repeat;
  background-size: cover;
  overflow: hidden;
}

.info-box{
  margin: 100px auto;
  width: 70%;
  height: 700px;
  display: flex;
  box-shadow: rgb(204, 219, 232) 3px 3px 6px 0px inset, rgba(255, 255, 255, 0.5) -3px -3px 6px 1px inset;
  background: rgba(255,255,255,0.7);
  .info-l{
    flex:1;
    border:1px solid red;
    
    .info-l-t{
      display: flex;
      flex-direction: column;
      border:1px solid white;
      align-items: center;
      padding: 50px 0;
      .user-name{
        margin-top: 20px;
      }
    }
    .info-l-b{
      margin-top: 50px;
      ul{
        display: flex;
        flex-direction: column;
        align-items: center;
        li{
          border: 1px solid #000;
          height: 50px;
          width: 70%;
          text-align: center;
          line-height: 50px;
          margin: 10px;
          -webkit-transform: perspective(1px) translateZ(0);
          transform: perspective(1px) translateZ(0);
          transition-duration: 0.3s;
          transition-property: transform;
          cursor: pointer;
          &:hover{
            -webkit-transform: scale(0.9);
            transform: scale(0.9);
          }
        }
      }
    }
  }

  .info-r{
    flex:4;
    border:1px solid blue;
    .info-r-title{
      text-align: center;
      margin: 10px 0;
    }
    .show-info{
      width: 50%;
      margin: 20px auto;
      padding: 20px;
      box-shadow: rgba(0, 0, 0, 0.09) 0px 2px 1px, rgba(0, 0, 0, 0.09) 0px 4px 2px, rgba(0, 0, 0, 0.09) 0px 8px 4px, rgba(0, 0, 0, 0.09) 0px 16px 8px, rgba(0, 0, 0, 0.09) 0px 32px 16px;
      border-radius: 5px;
      .el-form-item{
        margin: 25px 0;
      }
      .btns{
        display: flex;
        width: 20%;
         .el-form-item{
          width: 100px;
        }
      }
    }
  }
}

</style>